/**
 * 帖子列表页
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight,
  TouchableOpacity,
  Image,
  Dimensions,
  SectionList,
  AlertIOS,
} from 'react-native';
import {
  StackNavigator,
} from 'react-navigation';

import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Toast from 'react-native-root-toast';
import Config from '../common/config';
import Request from '../common/request';
import Topic from './topic';

let width = Dimensions.get('window').width;//获取视口宽度

class Forum extends React.Component {
  static navigationOptions = {
    title: "全部版块",
  };
  constructor(props) {
    super(props);
    this.state = {
      dataSource: []
    }
  }

  componentDidMount() {
    console.log("going to fetchFourms...");
    this.fetchForums();
  }

  fetchForums() {
    var self = this;
    Request.get(Config.api.forum)
    .then((response) => {
      console.log(response);
      if (response.ret == 0) {
        self.setState({dataSource: response.data});
      } else {
        Toast.show(response.msg);
      }
      
    })
  }

  onItemPress(item) {
    //console.log(item);
    this.props.navigation.navigate("Topic", {...item.item});
  }

  renderItem(item, index) {
    //console.log("render4Item: ", item);

    //return <Text style={styles.itemText}>{item.item.name}</Text>
    return (
      <TouchableOpacity
        onPress={() => {this.onItemPress(item)}}
      >
        <View style={styles.itemBox}>
          <Image style={styles.itemImage} source={require('../asset/image/avatar.jpg')}/>
          <Text style={styles.itemText}>{item.item.name}</Text>
        </View>
      </TouchableOpacity>
    )
  }

  itemSeparator() {
    return <View style={style=styles.itemSeparator}></View>
  }

  renderSectionHeader(section) {
    console.log("renderSectionHeader:", section);
    return <Text style={styles.sectionHeader}>{section.section.key}</Text>
  }

  onEndReached() {
    console.log("onEndReached...");
  }

  render() {
    return (
      <View style={styles.container}>
        <SectionList
          renderItem={this.renderItem.bind(this)}
          renderSectionHeader={this.renderSectionHeader}
          sections={this.state.dataSource}
          ItemSeparatorComponent={this.itemSeparator}
          onEndReached={this.onEndReached}
          onEndReachedThreshold={0.5}
        />
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  itemBox: {
    display: "flex",
    padding: 15,
    flexDirection: "row",
    alignItems: "center"
  },
  itemImage: {
    width: 32,
    height: 32,
    resizeMode: "contain",
    maxHeight: 50,
    marginRight: 10,
  },
  itemText: {

  },
  sectionHeader: {
    backgroundColor: "#ddd",
    padding: 15,
  },
  itemSeparator: {
    backgroundColor: "#ddd",
    height: 0.5,
    flex: 1,
    marginLeft: 47,
    marginRight: 15,
  }

});

module.exports = Forum;

